package cn.admin.configcenter.registry.common.info;

import cn.admin.config.common.Revision;
import cn.admin.configcenter.registry.common.util.SingletonRepository;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class GroupId {

	public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
	public final String dataId;
	public final String groupId;
	private boolean mannualUpdated = false;
	private final boolean isPersist;
	private final AtomicLong revision = new AtomicLong(1L);

	private GroupId(String dataId,String groupId) {
		this.dataId = dataId;
		this.groupId = groupId;
		this.isPersist = false;
	}

	public static GroupId getSingleton(String dataId,String groupId) {
		return SingletonRepository.getSingleton(new GroupId(dataId,groupId));
	}

	public static List<GroupId> allGroups() {
		List<GroupId> groups = new LinkedList<>();
		Iterator<Object> it = SingletonRepository.readOnlyIterator();
		while (it.hasNext()) {
			Object obj = it.next();
			if (obj instanceof  GroupId) {
				groups.add((GroupId) obj);
			}
		}
		return groups;
	}

	public boolean isPersist() {
		return this.isPersist;
	}

	public boolean isNonPersist() {
		return !this.isPersist;
	}

	public String getPersistString() {
		return this.isPersist ? "persist" : "non-persist";
	}

	public void increaseRevision() {
		this.revision.incrementAndGet();
	}

	public void setRevision(long rev) {
		this.revision.set(rev);
	}

	public Revision revision() {
		return new Revision(this.revision.get());
	}

	@Override
	public boolean equals(Object obj) {
		if (null != obj && obj.getClass() == this.getClass()) {
			if (this == obj) {
				return true;
			} else {
				GroupId other = (GroupId)obj;
				return this.dataId.equals(other.dataId) && this.groupId.equals(other.groupId);
			}
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return this.dataId.hashCode() * 31 + this.groupId.hashCode();
	}

	@Override
	public String toString() {
		return "GroupId[" + this.dataId + ", " + this.groupId + ", " + this.getPersistString() + "]";
	}

	public String getDataId() {
		return this.dataId;
	}

	public String getGroupId() {
		return this.groupId;
	}

	public void setMannualUpdated(boolean b) {
		this.mannualUpdated = b;
	}

	public boolean isMannualUpdated() {
		return this.mannualUpdated;
	}
}
